package com.apkicon.test;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import com.apkicon.parser.ApkResourceResolver;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 深度分析test.apk的所有图标资源
 * 查找可能被遗漏的蓝色前景资源
 */
public class DeepIconResourceAnalyzer {
    
    public static void main(String[] args) {
        try {
            System.out.println("Deep Analysis of test.apk Icon Resources");
            System.out.println("=========================================");
            
            try (ApkFile apkFile = new ApkFile("test.apk")) {
                // 1. 分析APK基本信息
                ApkMeta apkMeta = apkFile.getApkMeta();
                System.out.println("APK Info:");
                System.out.println("  Package: " + apkMeta.getPackageName());
                System.out.println("  App Name: " + apkMeta.getLabel());
                System.out.println("  Icon Path: " + apkMeta.getIcon());
                System.out.println();
                
                // 2. 查找所有PNG资源
                System.out.println("Searching for all PNG resources...");
                findAndAnalyzeAllPngResources(apkFile);
                
                // 3. 分析Adaptive Icon XML
                System.out.println("\nAnalyzing Adaptive Icon XML...");
                analyzeAdaptiveIconXml(apkFile, apkMeta.getIcon());
                
                // 4. 查找可能的蓝色资源
                System.out.println("\nSearching for blue-colored resources...");
                findBlueResources(apkFile);
                
            }
            
        } catch (Exception e) {
            System.err.println("Analysis failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static void findAndAnalyzeAllPngResources(ApkFile apkFile) throws IOException {
        // 已知的资源文件列表
        String[] knownResources = {
            "res/qD.9.png",      // 背景
            "res/-B.png",        // 前景
            "res/BM.png",        // 可能的另一个前景
            "res/1I.9.png",      // 其他资源
            "res/zV.9.png",      // 其他资源
            "res/NA.9.png",      // 其他资源
            "res/MF.9.png",      // 其他资源
            "res/ej.9.png",      // 其他资源
            "res/hZ.9.png",      // 其他资源
            "res/jS1.9.png",     // 其他资源
            "res/1e.9.png",      // 其他资源
            "res/Wh.png",        // 其他资源
            "res/_q.png"         // 其他资源
        };
        
        for (String resourcePath : knownResources) {
            byte[] data = apkFile.getFileData(resourcePath);
            if (data != null) {
                System.out.println("Found resource: " + resourcePath + " (" + data.length + " bytes)");
                
                // 分析图片
                try {
                    BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
                    if (image != null) {
                        analyzeImageColors(image, resourcePath);
                    }
                } catch (Exception e) {
                    System.out.println("  Failed to analyze image: " + e.getMessage());
                }
            }
        }
    }
    
    private static void analyzeImageColors(BufferedImage image, String resourcePath) {
        System.out.println("  Image analysis for " + resourcePath + ":");
        System.out.println("    Size: " + image.getWidth() + "x" + image.getHeight());
        System.out.println("    Type: " + getImageType(image));
        
        // 分析主要颜色
        Map<Integer, Integer> colorCount = new HashMap<>();
        int width = image.getWidth();
        int height = image.getHeight();
        
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                int alpha = (rgb >> 24) & 0xFF;
                
                if (alpha > 0) {
                    colorCount.put(rgb, colorCount.getOrDefault(rgb, 0) + 1);
                }
            }
        }
        
        // 显示最常见的颜色
        System.out.println("    Most common colors:");
        colorCount.entrySet().stream()
            .sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))
            .limit(5)
            .forEach(entry -> {
                int rgb = entry.getKey();
                int count = entry.getValue();
                int alpha = (rgb >> 24) & 0xFF;
                int red = (rgb >> 16) & 0xFF;
                int green = (rgb >> 8) & 0xFF;
                int blue = rgb & 0xFF;
                
                System.out.printf("      #%08X RGB(%d,%d,%d) Alpha:%d - %d pixels\n", 
                                rgb, red, green, blue, alpha, count);
            });
        
        // 检查是否有蓝色
        boolean hasBlue = colorCount.keySet().stream()
            .anyMatch(rgb -> {
                int red = (rgb >> 16) & 0xFF;
                int green = (rgb >> 8) & 0xFF;
                int blue = rgb & 0xFF;
                return blue > red && blue > green && blue > 100;
            });
        
        if (hasBlue) {
            System.out.println("    *** CONTAINS BLUE COLORS! ***");
        }
        
        System.out.println();
    }
    
    private static void analyzeAdaptiveIconXml(ApkFile apkFile, String iconPath) throws IOException {
        byte[] xmlData = apkFile.getFileData(iconPath);
        if (xmlData != null) {
            String xmlContent = new String(xmlData);
            System.out.println("XML Content:");
            System.out.println(xmlContent);
            System.out.println();
            
            // 解析XML中的资源引用
            ApkResourceResolver.AdaptiveIconResources resources = 
                ApkResourceResolver.resolveAdaptiveIconResources(apkFile, iconPath);
            
            System.out.println("Parsed Resources:");
            System.out.println("  Background: " + resources.getBackgroundPath());
            System.out.println("  Foreground: " + resources.getForegroundPath());
            System.out.println();
        }
    }
    
    private static void findBlueResources(ApkFile apkFile) throws IOException {
        String[] resourcesToCheck = {
            "res/-B.png",        // 当前前景
            "res/BM.png",        // 可能的另一个前景
            "res/Wh.png",        // 其他资源
            "res/_q.png"         // 其他资源
        };
        
        for (String resourcePath : resourcesToCheck) {
            byte[] data = apkFile.getFileData(resourcePath);
            if (data != null) {
                try {
                    BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
                    if (image != null) {
                        if (containsBlueColors(image)) {
                            System.out.println("*** BLUE FOUND in " + resourcePath + " ***");
                            
                            // 保存这个资源用于分析
                            String fileName = resourcePath.replace("/", "_").replace(".", "_") + ".png";
                            ImageIO.write(image, "PNG", new File(fileName));
                            System.out.println("Saved as: " + fileName);
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Failed to analyze " + resourcePath + ": " + e.getMessage());
                }
            }
        }
    }
    
    private static boolean containsBlueColors(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                int alpha = (rgb >> 24) & 0xFF;
                
                if (alpha > 0) {
                    int red = (rgb >> 16) & 0xFF;
                    int green = (rgb >> 8) & 0xFF;
                    int blue = rgb & 0xFF;
                    
                    // 检查是否是蓝色（蓝色分量明显大于红色和绿色）
                    if (blue > red + 50 && blue > green + 50 && blue > 100) {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
    
    private static String getImageType(BufferedImage image) {
        switch (image.getType()) {
            case BufferedImage.TYPE_INT_RGB: return "RGB";
            case BufferedImage.TYPE_INT_ARGB: return "ARGB";
            case BufferedImage.TYPE_INT_ARGB_PRE: return "ARGB_PRE";
            case BufferedImage.TYPE_4BYTE_ABGR: return "4BYTE_ABGR";
            case BufferedImage.TYPE_4BYTE_ABGR_PRE: return "4BYTE_ABGR_PRE";
            case BufferedImage.TYPE_3BYTE_BGR: return "3BYTE_BGR";
            case BufferedImage.TYPE_BYTE_GRAY: return "BYTE_GRAY";
            case BufferedImage.TYPE_USHORT_GRAY: return "USHORT_GRAY";
            case BufferedImage.TYPE_BYTE_BINARY: return "BYTE_BINARY";
            case BufferedImage.TYPE_BYTE_INDEXED: return "BYTE_INDEXED";
            default: return "UNKNOWN (" + image.getType() + ")";
        }
    }
}
